var express = require('express');
var router = express.Router();
var qiniu = require('qiniu');
var rpcFunc=require('../routes/rpcSrv/rpcFunc.js');
var superagent = require('superagent');

var tgUtil = require('./util/tgUtil')
var ItbUserModel = require('../../common/mysql/mapping/ItbUserModel');
var TgDesignDocModel = require('../../common/mysql/mapping/TgDesignDocModel');
var TgDesignPageModel = require('../../common/mysql/mapping/TgDesignPageModel');
var TgUserDocModel = require('../../common/mysql/mapping/TgUserDocModel');
var TgUserPageModel = require('../../common/mysql/mapping/TgUserPageModel');
var TgUserPcModel = require('../../common/mysql/mapping/TgUserPcModel');
var TgTypeModel = require('../../common/mysql/mapping/TgTypeModel');
var OSSMgr = require('../../common/util/OSSMgr');
var CONFIG = require('../../common/config');
var CODE = require('../../common/code');

var async = require( 'async'); // 同步控制

var moment = require('moment');  // 日期格式化

var BASE_IP = CONFIG.BASE_IP;


//------------------------------------------------------------------
/* 获取分类信息
 * 方式:GET/POST
 * 参数 device:
 * 参数 uuid: 设备标识
 * 参数 typeL: 大分类id [1:竖屏(默认), 2:ppt]
 * 返回: 二级结构
     [
         {
             id: 10,
             name: "邀请函",
             sub:[{id:101, name:“开业”}, {id:102, name:"讲座"} ...]
         },
         {
             id: 30,
             name: "招聘",
             sub:[{id:301, name:“校招”}, {id:302, name:"社招"} ...]
         }
     ]
 * */
function getTypeInfo(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var typeL = Number(req.body.typeL || req.query.typeL || '1');

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // 获取文档
    var entity = new TgTypeModel({
        typeL: typeL,
        typeM: '10,20,50,80',// TODO 客户端暂时只显示[邀请函/促销推广/通知/个人(婚礼)]
        state:3, //`state` int(2) NOT NULL DEFAULT '1' COMMENT '1新建,2可制作模版,3可对外发布',
        withAny: true
    });
    entity.getTypeInfoByLMS(function (err, rets) {
        if (err) {
            console.log('tg.js [getTypeInfo] get Err: ' + err);
            return ret_func(0, CODE.OPERATION_FAILED);
        }

        return ret_func(1,CODE.OPERATION_SUCCESS, rets);
    });

}
router.get('/getTypeInfo', getTypeInfo);
router.post('/getTypeInfo', getTypeInfo);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取[设计模版]列表
 * 方式:GET
 * 参数 device: 请求来源
 * 参数 uuid: 设备标识
 * 参数 typeM: (typeM<=0):最新, (typeM>0):中分类id
 * 参数 typeS［可选］: 小分类id
 * 参数 pageNum: 页码,从0开始[默认为0]
 * 参数 pageSize: 每页容量[0或空:忽略pageNum获取全部记录]
 * 参数 withTotalPage［可选］:1表示需要返回总页数
 * */
function getDesignList(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var typeM = Number(req.body.typeM || req.query.typeM || 0);
    var typeS = Number(req.body.typeS || req.query.typeS || 0);
    var pageNum = Number(req.body.pageNum || req.query.pageNum || 0);
    var pageSize = Number(req.body.pageSize || req.query.pageSize || 0);
    var withTotalPage = Number(req.body.withTotalPage || req.query.withTotalPage || 0);

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // check parameter
    if (typeof typeM=='undefined' || isNaN(typeM) || typeM==null) {
        return ret_func(0,"分类未指定");
    }

    //if (typeof pageSize=='undefined' || isNaN(pageSize) || pageSize==null || pageSize==0) {
    //    return ret_func(0,CODE.PAGENUM_EMPTY);
    //}

    // 分页: 跳过条数
    var skipCnt = pageNum * pageSize;
    var typeL = 1; // 对于旧版本，只能查询到“单页数据”

    function proc_func(items, totalPageCount) {
        var retData = [];
        for (var i in items) {
            var item = items[i];
            var itemData = {
                "designId": item.design_id,
                "thumb": item.thumb,
                "name": item.design_name,
                "createTime": item.create_time,
                "updateTime": item.update_time,
                //"pageCount": item.page_count
            }
            if(withTotalPage>=0){
                itemData.totalPageCount = totalPageCount;
            }
            retData.push(itemData);
        }
        return ret_func(1,CODE.OPERATION_SUCCESS,retData);
    }

    var entity = new TgDesignDocModel({
        publish: 1,
    });
    // 分页查询
    entity.getDocAndPagesInfoByType(function(err, items){
        if (err){
            console.log('tg.js [getDesignList] getInfo Err: '+err);
            return ret_func(0,CODE.OPERATION_FAILED);
        }
        if(withTotalPage>0){
            entity.getDocAndPagesInfoByTypeCnt(function(err2, count){
                if (err2){
                    console.log('tg.js [getDesignList] getInfo Cnt Err: '+err2);
                    return ret_func(0,CODE.OPERATION_FAILED);
                }

                var pgCnt = 1;
                if(pageSize>0) {
                    pgCnt = Math.floor((count-1)/pageSize)+1;
                }
                proc_func(items, pgCnt);
            }, typeM, typeS, typeL);

        }else{
            proc_func(items);
        }

    }, typeM, typeS, typeL, skipCnt, pageSize);

}
router.get('/getDesignList', getDesignList);
router.post('/getDesignList', getDesignList);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取[个人中心]信息
 * 方式:GET
 * 参数 device: 请求来源
 * 参数 uuid: 设备标识
 * 参数 userId: 用户ID
 * 参数 orderBy: 0或空:doc_id顺序, 1:create_time倒序
 * 参数 pageNum: 页码,从0开始[默认为0]
 * 参数 pageSize: 每页容量[0或空:忽略pageNum获取全部记录]
 * 参数 retFlg: 0或空:返回下列所有信息(默认), 1:只返回文档id [优先级高于track]
 * 参数 track: 0或空:不返回追踪信息(默认), 1:返回文档追踪信息
 * 参数 withTotalPage[可选]: 1表示需要返回总页数
 * 参数 typeL: 0 未分类   1 海报  2 多页  3 ppt.
 * 返回:
 * {
 *   success: 1,
 *   msg: 成功,
 *   data: [
 *     {
 *       doc_id: 111, // 用户文档id
 *       design_id: 12, // 设计模版id
 *       create_time: "2016-04-27 09:30:56",
 *       thumb: "http://xxxx.jpg",
 *       name: "文档名称",
 *       track: 1,// 是否追踪
 *       trackInfo: {
 *            read: 10,       // 阅读次数
 *            duration: 250,  // 阅读秒数
 *            relay: 10,      // 转发次数
 *            collect: 1,     // 1:已收藏, 0:未收藏 (暂无)
 *         }
 *     },
 *     ...
 *   ]
 * }
 * */
function getUserCenterInfo(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var userId = Number(req.body.userId || req.query.userId || 0);
    var track = req.body.track || req.query.track || 0;
    var pageNum = Number(req.body.pageNum || req.query.pageNum || 0);
    var pageSize = Number(req.body.pageSize || req.query.pageSize || 0);
    var orderBy = req.body.orderBy || req.query.orderBy || 0;
    var retFlg = req.body.retFlg || req.query.retFlg || 0;
    var withTotalPage = req.body.withTotalPage || req.query.withTotalPage || 0;
    var typeL = Number(req.body.typeL || req.query.typeL || 1);

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // check parameter
    if((typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0)) {
        return ret_func(0,CODE.USER_ID_EMPTY);
    }
    //if(typeof pageNum=='undefined' || pageNum == null){
    //    return ret_func(0,CODE.PAGENUM_EMPTY);
    //}
    //if(typeof pageSize=='undefined' || pageSize == null || pageSize == 0){
    //    return ret_func(0,CODE.PAGESIZE_EMPTY);
    //}

    // 分页: 跳过条数
    var skipCnt = pageNum * pageSize;

    var entity = new TgUserDocModel({
        user_id: userId,
    });
    entity.getDocInfoByUser(function(err, results){
        if (err) {
            console.log('tg.js [getUserCenterInfo] find doc err: '+err);
            return ret_func(0,CODE.OPERATION_FAILED);
        }

        function processData(totalPageCount){
            var retData = [];
            var docIds = '';
            if (results != null && results.length > 0) {
                for (var i in results){
                    var item = results[i];
                    if (0 == i) {
                        docIds = item.doc_id;
                    } else {
                        docIds += (',' + item.doc_id);
                    }

                    var itemData = {};
                    if (retFlg == 1) {
                        itemData.doc_id = item.doc_id;
                        itemData.design_id = item.design_id;
                    } else {
                        itemData.doc_id = item.doc_id;
                        itemData.design_id = item.design_id;
                        itemData.create_time = item.create_time || '';
                        itemData.thumb = item.thumb || '';
                        itemData.name = item.doc_name || '';
                        itemData.track = item.track || 0;
                    }
                    if(withTotalPage){
                        itemData.totalPageCount=totalPageCount;
                    }
                    retData.push(itemData);
                }
            }

            if (track == 1 && retFlg == 0 && docIds.length>0) {
                var entity2 = new TgUserDocModel({
                    ids:docIds,
                    type: 0
                });
                entity2.getTrackInfoById(function(err2, items){
                    if (err2) {
                        console.log('tg.js [getUserCenterInfo] Get TrackInfo Err: '+err2);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    if (items != null && items.length > 0) {
                        for (var n in items){
                            var trackItem = items[n];
                            for (var j in retData){
                                if (trackItem.doc_id == retData[j].doc_id){
                                    var trackData = {
                                        read: trackItem.read_cnt || 0,
                                        duration: trackItem.duration || 0,
                                        relay: trackItem.relay_cnt || 0,
                                    }
                                    retData[j].trackInfo = trackData;
                                    break;
                                }
                            }
                        }
                    }
                    return ret_func(1,CODE.OPERATION_SUCCESS,retData);
                });

            } else {
                return ret_func(1,CODE.OPERATION_SUCCESS,retData);
            }
        }

        if(withTotalPage){
            entity.getDocInfoByUserCnt(function(err, count) {
                if (err) {
                    console.log('tg.js [getUserCenterInfo] Get Count Err: ' + err);
                    return ret_func(0,CODE.OPERATION_FAILED);
                }

                var pgCnt = 1;
                if(pageSize>0) {
                    pgCnt = Math.floor((count-1)/pageSize)+1;
                }
                processData(pgCnt);
            }, typeL);
        }else{
            processData(0);
        }

    }, skipCnt, pageSize, orderBy, typeL);
}
router.get('/getUserCenterInfo', getUserCenterInfo);
router.post('/getUserCenterInfo', getUserCenterInfo);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 移动端－保存用户文档,不排版.
 * 方式:POST
 * 参数 device: 请求来源
 * 参数 uuid: 设备唯一标识符
 * 参数 userId: 用户id(*不能为空)
 * 参数 clrHis[可选]: 是否删除切换模版历史记录(等于1时删除,默认不删除)
 * 参数 skipUserChk[可选]: 是否检查用户(等于1时不检查,默认检查)
 * 参数 doc: 移动端文档的json字符串(树状结构)
 * {
 *      "designId": 321,
 *      "productId": 789,
 *      "productNm": 'doc name',
 *      "tag":[10,1,5,1...],
 *      "coreStructure": {
 *          "version":"1",
 *          "name":"会议邀请函脑图",
 *          "root":{...}
 *      }
 * }
 * 参数 typeL: 0 未分类   1 海报  2 多页  3 ppt.  4. 印品 //  从5.x开始增加此参数，注意之前的接口没有此参数
 * */
function saveUserDocOnly(req, res, next) {

    // get parameter
    var device = req.body.device || req.query.device;
    var docStr = req.body.doc || req.query.doc;
    var doc = JSON.parse(docStr);
    var userId = Number(req.body.userId || req.query.userId || 0);
    var uuid = req.body.uuid || req.query.uuid;
    var clrHis = Number(req.body.clrHis || req.query.clrHis || "0");
    var skipUserChk = Number(req.body.skipUserChk || req.query.skipUserChk || "0");
    var typeL = req.body.typeL || req.query.typeL;
    if(CONFIG.DEBUG==1)    clrHis = 0;

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // check parameter
    if(typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
        return ret_func(0,CODE.UUID_EMPTY);
    }
    if((typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0)) {
        return ret_func(0,CODE.USER_ID_EMPTY);
    }
    if(typeof doc=='undefined' || doc == null){
        return ret_func(0,CODE.DOC_DATA_EMPTY);
    }else {
        if(doc.designId=='undefined' || doc.designId==null) {
            return ret_func(0,"设计模版ID为空");
        }
    }

    // proc
    async.parallel({
        getDesign: function(callback){
            // 检索design
            var entityD = new TgDesignDocModel({
                design_id: doc.designId,
                del_flg: 0
            });
            entityD.findFromDB(function(err, items) {
                if (err) {
                    console.log('tg.js [saveUserDocOnly] Check design_id Err: ' + err);
                    return callback(err, null);
                }

                if (items != null && items.length > 0) {
                    return callback(null, items[0]);

                } else {
                    console.log('tg.js [saveUserDocOnly] design_id invalid ');
                    return callback("无效DESIGN_ID", null);
                }
            });
        },

        getUser: function(callback){
            if(skipUserChk == 1){
                // 直接返回
                return callback(null, {user_id: userId, user_type:1});
            } else {
                // 检索user
                var entity = new ItbUserModel({
                    //uuid    : uuid,
                    user_id : userId,
                    del_flg : 0
                });
                entity.findFromDB(function(err, items){
                    if (err){
                        console.log('tg.js [saveUserDocOnly] Check user_id Err: '+err);
                        return callback(error, null);
                    }

                    if (items != null && items.length > 0) {
                        return callback(null, items[0]);

                    } else {
                        console.log('tg.js [saveUserDocOnly] user_id invalid ');
                        return callback(CODE.USER_ID_INVAILD, null);
                    }
                });
            }
        }

    }, function(error, result){
        if (error) {
            return ret_func(0,CODE.OPERATION_FAILED);
        }

        var userItem = result.getUser;
        var designItem = result.getDesign;

        if (doc.productId=='undefined' || doc.productId==null || Number(doc.productId)==0) {
            // 新规
            var newDocEntity = new TgUserDocModel({
                tg_id: designItem.tg_id,
                map_id: designItem.map_id,
                design_id: designItem.design_id,
                doc_name: doc.productNm || '我的作品',// doc.coreStructure.name
                user_id: userItem.user_id,
                user_type: userItem.user_type,
                purpose: 0,
                size_id: designItem.size_id,
                type_id: designItem.type_id,
                data: JSON.stringify(doc.coreStructure) || '',
                hash_tag: JSON.stringify(doc.tag) || '[]',// TODO
                ver: doc.coreStructure.version || 0,
                update_by: userItem.user_id,
            });
            // insert document
            newDocEntity.saveToDB(function(err, newDocId){
                if (err) {
                    console.log('tg.js [saveUserDocOnly] Ins Doc Err: '+err);
                    return ret_func(0,CODE.OPERATION_FAILED);
                }

                // 新建pages
                //var pageEnt = new TgUserPageModel({
                //    doc_id: newDocId,
                //    update_by: userItem.user_id
                //});
                //pageEnt.copyPageFromDesign(function(err3){
                //    if (err3) {
                //        console.log('tg.js [saveUserDocOnly] Ins Pages Err: '+err3);
                //        return ret_func(0,CODE.OPERATION_FAILED);
                //    }
                //
                //    // 新建pc
                //    var pcEnt = new TgUserPcModel({
                //        doc_id: newDocId,
                //        update_by: userItem.user_id
                //    });
                //    pcEnt.copyPcFromDesign(function(err4){
                //        if(err4) {
                //            console.log('tg.js [saveUserDocOnly] Ins PCs Err: '+err4);
                //            return ret_func(0,CODE.OPERATION_FAILED);
                //        }

                        var retData = {
                            designId: designItem.design_id,
                            productId: newDocId,
                        };

                        return ret_func(1,CODE.OPERATION_SUCCESS,retData);

                //    }, designItem.design_id);
                //}, designItem.design_id);
            });

        } else {
            // 更新doc
            var updDocEnt = new TgUserDocModel({
                doc_id: doc.productId,// Key
                doc_name: doc.productNm || '我的作品',// doc.coreStructure.name
                data: JSON.stringify(doc.coreStructure) || '',
                hash_tag: JSON.stringify(doc.tag) || '[]',// TODO
                ver: doc.coreStructure.version || 0,
                update_by: userItem.user_id,
            });
            updDocEnt.updateToDB(function(err){
                if (err) {
                    console.log('tg.js [saveUserDocOnly(upd)] Upd Doc Err: '+err);
                    return ret_func(0,CODE.OPERATION_FAILED);
                }

                //****************************************
                // 更新page
                //var updPgEnt = new TgUserPageModel({
                //    doc_id: doc.productId,
                //    update_by: userItem.user_id,
                //});
                //updPgEnt.updPageFromDesign(function(err2){
                //    if (err2) {
                //        console.log('tg.js [saveUserDocOnly] Upd Page Err: '+err2);
                //        return ret_func(0,CODE.OPERATION_FAILED);
                //    }
                //
                //    // 更新pc
                //    var updPcEnt = new TgUserPcModel({
                //        doc_id: doc.productId,
                //        update_by: userItem.user_id,
                //    });
                //    updPcEnt.updPcFromDesign(function(err3){
                //        if (err3) {
                //            console.log('tg.js [saveUserDocOnly] Upd Pc Err: '+err3);
                //            return ret_func(0,CODE.OPERATION_FAILED);
                //        }
                //
                //        // 返回值
                //        var retData = {
                //            designId: designItem.design_id,
                //            productId: doc.productId,
                //        };
                //
                //        if(1==clrHis){
                //            // 清除切换历史
                //            doClrHis(doc.productId, function(clrErr, clrRet){
                //                if (clrErr) {
                //                    console.log('tg.js [saveUserDocOnly] doClrHis Err: '+clrErr);
                //                    return ret_func(0,CODE.OPERATION_FAILED);
                //                }
                //                return ret_func(1,CODE.OPERATION_SUCCESS,retData);
                //            });
                //
                //        } else {
                //            return ret_func(1,CODE.OPERATION_SUCCESS,retData);
                //        }
                //
                //    }, designItem.design_id);
                //}, designItem.design_id);
                //****************************************

                // 逻辑删除page
                var delPgEnt = new TgUserPageModel({
                    doc_id: doc.productId,
                    update_by: userItem.user_id,
                });
                delPgEnt.delPageLogic(function(delErr){
                    if (delErr) {
                        console.log('tg.js [saveUserDocOnly(upd)] Del Pages Err: ' + delErr);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    // 逻辑删除pc
                    var delPcEnt = new TgUserPcModel({
                        doc_id: doc.productId,
                        update_by: userItem.user_id,
                    });
                    delPcEnt.delPcLogic(function(delErr2){
                        if (delErr2) {
                            console.log('tg.js [saveUserDocOnly(upd)] Del PCs Err: ' + delErr2);
                            return ret_func(0,CODE.OPERATION_FAILED);
                        }

                        // 新建pages
                        //var newPgEnt = new TgUserPageModel({
                        //    doc_id: doc.productId,
                        //    update_by: userItem.user_id
                        //});
                        //newPgEnt.copyPageFromDesign(function(insErr){
                        //    if (insErr) {
                        //        console.log('tg.js [saveUserDocOnly(upd)] Ins Pages Err: '+insErr);
                        //        return ret_func(0,CODE.OPERATION_FAILED);
                        //    }
                        //
                        //    // 新建pc
                        //    var newPcEnt = new TgUserPcModel({
                        //        doc_id: doc.productId,
                        //        update_by: userItem.user_id
                        //    });
                        //    newPcEnt.copyPcFromDesign(function(insErr2){
                        //        if(insErr2) {
                        //            console.log('tg.js [saveUserDocOnly(upd)] Ins PCs Err: '+insErr2);
                        //            return ret_func(0,CODE.OPERATION_FAILED);
                        //        }

                                // 返回值
                                var retData = {
                                    designId: designItem.design_id,
                                    productId: doc.productId,
                                };

                                if(1==clrHis){
                                    // 清除切换历史
                                    doClrHis(doc.productId, function(clrErr, clrRet){
                                        if (clrErr) {
                                            console.log('tg.js [saveUserDocOnly(upd)] doClrHis Err: '+clrErr);
                                            return ret_func(0,CODE.OPERATION_FAILED);
                                        }
                                        return ret_func(1,CODE.OPERATION_SUCCESS,retData);
                                    });

                                } else {
                                    return ret_func(1,CODE.OPERATION_SUCCESS,retData);
                                }

                        //    }, designItem.design_id);
                        //}, designItem.design_id);
                    });
                });

            });
        }
    });

    // 删除切换模版记录
    function doClrHis(docId,callback){
        var url = CONFIG.SWITCH_SERVER_DOMAIN +':'+CONFIG.SWITCH_SERVER_PORT+'/tgSwitch/clrSwitchHis?'
            +'docId='+docId;

        superagent.get(url)
            .end(function(err, res){
                if(err){
                    console.log('tg.js [saveUserDocOnly] SuperAgent clrSwitchHis Err: ' + err);
                    return callback(err, null);
                }

                var retJson = JSON.parse(res.text);
                if(retJson.success){
                    return callback(null,retJson.data);

                } else {
                    return callback(retJson.msg, null);
                }
            }
        );
    }
}
router.get('/saveUserDocOnly', saveUserDocOnly);
router.post('/saveUserDocOnly', saveUserDocOnly);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取[设计模版]或[用户作品]数据
 * 方式:GET
 * 参数 device: 请求来源
 * 参数 uuid: 设备标识
 * 参数 userId: 用户id
 * 参数 docId: 文档id
 * 参数 isDesign: 1:docId为[设计模版]文档id, 0或空:docId为[用户作品]文档id
 * 参数 typeL: 0 未分类   1 海报  2 多页  3 ppt.  4. 印品 //  从5.x开始增加此参数，注意之前的接口没有此参数
 * */
function getDocInfo(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var userId = Number(req.body.userId || req.query.userId || 0);
    var docId = Number(req.body.docId || req.query.docId || 0);
    var isDesign = Number(req.body.isDesign || req.query.isDesign || 0);
    var typeL = req.body.typeL || req.query.typeL;

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // check parameter
    if (typeof docId=='undefined' || isNaN(docId) || docId==null || docId==0) {
        return ret_func(0,"文档id为空");
    }
    if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
        return ret_func(0,"用户id为空");
    }

    var entity = null;
    if(isDesign) {
        entity = new TgDesignDocModel({
            design_id: docId,
            del_flg: 0
        });
    } else {
        entity = new TgUserDocModel({
            doc_id: docId,
            del_flg: 0
        });
    }
    entity.findFromDB(function(err,items) {
        if (err) {
            console.log('tg.js [getDocInfo] Find Err: ' + err);
            return ret_func(0, CODE.OPERATION_FAILED);
        }

        if(items && items.length>0) {
            // 替换非法字符
            var strFtData = items[0].data
                .replace(/\n/g,'\\n').replace(/\t/g,'').replace(/\r/g,'') //.replace(/\\"/g,'\\\\\\"')
                .replace(/[\x00-\x09\x0B-\x1F\x7F-\x9F]/g, "");
            var retData = {
                designId: items[0].design_id,
                designNm: items[0].design_name||'',
                productId: items[0].doc_id||0,
                productNm: items[0].doc_name||'',
                coreStructure: JSON.parse(strFtData||'{}')
            };

            return ret_func(1, CODE.OPERATION_SUCCESS, retData);

        } else {
            return ret_func(0, "未找到数据");
        }
    });

}
router.get('/getDocInfo', getDocInfo);
router.post('/getDocInfo', getDocInfo);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取[设计模版]数据
 * 方式:GET
 * 参数 device: 请求来源
 * 参数 uuid: 设备标识
 * 参数 typeM: 中分类
 * 参数 typeS: 小分类
 * 参数 mode[可选]: 0或空:按照order和updateTime取第一个, 1:随机取一个
 * */
function getDesignInfoByType(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var typeM = Number(req.body.typeM || req.query.typeM || 0);
    var typeS = Number(req.body.typeS || req.query.typeS || 0);
    var mode = Number(req.body.mode || req.query.mode || 0);
    var typeL = 1; // 对于旧版本，只能查询到“单页数据”

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // check parameter
    if (typeof typeM=='undefined' || isNaN(typeM) || typeM==null || typeM==0) {
        return ret_func(0,"中分类为空");
    }
    //if (typeof typeS=='undefined' || isNaN(typeS) || typeS==null || typeS==0) {
    //    return ret_func(0,"小分类为空");
    //}

    var pageSize = 1;
    if(mode == 1) {
        pageSize = 0;
    }

    var entity = new TgDesignDocModel({
        publish:1
    });
    // 分页查询
    entity.getDocAndPagesInfoByType(function(err, items) {
        if (err) {
            console.log('tg.js [getDesignInfoByType] getInfo Err: ' + err);
            return ret_func(0, CODE.OPERATION_FAILED);
        }

        if(items && items.length>0) {
            var item = items[0];
            if(mode == 1) {// 随机
                item = items[Math.floor(Math.random() * items.length)];
            }

            var retData = {
                productId: 0,
                designId: item.design_id,
                coreStructure: JSON.parse(item.data)
            }
            return ret_func(1,CODE.OPERATION_SUCCESS,retData);

        } else {
            return ret_func(0, "未找到数据");
        }

    },typeM, typeS,typeL, 0, pageSize);

}
router.get('/getDesignInfoByType', getDesignInfoByType);
router.post('/getDesignInfoByType', getDesignInfoByType);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 用户文档重命名
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 uuid: 设备唯一标识符
 * 参数 userId: 用户ID
 * 参数 docId: 文档ID
 * 参数 docName: 文档名称
 * 返回值: {
 *           success: 1,
 *           msg: 成功,
 *           data: {old_name:XXX, new_name:YYY}
 *        }
 * */
function setUserDocName(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var userId = Number(req.body.userId || req.query.userId || '0');
    var docId = Number(req.body.docId || req.query.docId || '0');
    var docName = req.body.docName || req.query.docName || '';

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // check parameter
    if(typeof docId=='undefined' || isNaN(docId) || docId==null || docId==0) {
        return ret_func(0,CODE.DOC_ID_EMPTY);
    }
    if(typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
        return ret_func(0,CODE.USER_ID_EMPTY);
    }

    // 检索文档
    var entity = new TgUserDocModel({
        doc_id : docId,
        user_id: userId,
        del_flg: 0
    });
    entity.findFromDB(function(err,items){
        if (err) {
            console.log('tg.js [setUserDocName] Find Doc Err: ' + err);
            return ret_func(0,CODE.OPERATION_FAILED);
        }

        if (items!=null && items.length>0) {
            var docInfo = items[0];
            if (docInfo.user_type == 1){
                // 更新
                var updEnt = new TgUserDocModel({
                    doc_id: docId,
                    doc_name: docName,
                    update_by: userId
                });
                updEnt.updateToDB(function(error,ret){
                    if (error) {
                        console.log('tg.js [setUserDocName] Upd Doc Err: ' + error);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    var retData = {
                        old_name: docInfo.doc_name,
                        new_name: docName
                    };
                    return ret_func(1,CODE.OPERATION_SUCCESS,retData);
                });

            } else {
                return ret_func(0,"不能重命名非用户文档");
            }

        } else {
            return ret_func(0,"未找到目标文档");
        }
    });
}
router.get('/setUserDocName', setUserDocName);
router.post('/setUserDocName', setUserDocName);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 删除用户文档
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 uuid: 设备唯一标识符
 * 参数 userId: 用户ID
 * 参数 docId: 文档ID
 * 返回值: {
 *           success: 1,
 *           msg: 成功,
 *        }
 * */
function delUserDoc(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var userId = Number(req.body.userId || req.query.userId || '0');
    var docId = Number(req.body.docId || req.query.docId || '0');

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // check parameter
    if(typeof docId=='undefined' || isNaN(docId) || docId == null || docId == 0){
        return ret_func(0,CODE.DOC_ID_EMPTY);
    }
    // user_id和uuid必须有一个存在
    var is_user_id_empty = false;
    var is_uuid_empty = false;
    if(typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
        is_user_id_empty = true;
    }
    if(typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
        is_uuid_empty = true;
    }
    if(is_user_id_empty && is_uuid_empty){
        return ret_func(0,CODE.USER_ID_EMPTY+CODE.UUID_EMPTY);
    }

    // 用user_id/uuid检索user信息
    var chkEntity = null;
    if (userId != null && userId>0){
        // user_id检索
        chkEntity = new ItbUserModel({
            user_id:userId,
            del_flg:0
        });
    } else {
        // uuid检索
        chkEntity = new ItbUserModel({
            uuid:uuid,
            del_flg:0
        });
    }
    chkEntity.findFromDB(function(err, users){
        if(err){
            console.log('tg.js [delUserDoc] Find User err:'+err);
            return ret_func(0,CODE.OPERATION_FAILED);
        }

        // 用户存在时
        if (users != null && users.length > 0){
            var user = users[0];

            var entity = new TgUserDocModel({
                doc_id: docId,
                del_flg: 0
            });
            // 检索文档
            entity.findFromDB(function(error, items){
                // process error
                if(error){
                    console.log('tg.js [delUserDoc] Find Doc err:'+error);
                    return ret_func(0,CODE.OPERATION_FAILED);
                }

                // 文档存在时
                if (items != null && items.length > 0) {
                    if (items[0].user_id != user.user_id) {
                        console.log('tg.js [delUserDoc] Del Doc Not Allowed');
                        return ret_func(0,CODE.DELETE_DOC_NOT_ALLOWED);
                    }

                    // 删除doc
                    var updEnt = new TgUserDocModel({
                        doc_id: docId,
                        user_id: userId,
                        del_flg: 1,
                        update_by: userId
                    });
                    updEnt.updateToDB(function(updErr){
                        if (updErr) {
                            console.log('tg.js [delUserDoc] Del Doc Err: ' + updErr);
                            return ret_func(0,CODE.OPERATION_FAILED);
                        }

                        // 删除pages
                        var updEnt2 = new TgUserPageModel({
                            doc_id: docId,
                            update_by: userId
                        });
                        updEnt2.delPageLogic(function(updErr2){
                            if (updErr2) {
                                console.log('tg.js [delUserDoc] Del Pages Err: ' + updErr2);
                                return ret_func(0,CODE.OPERATION_FAILED);
                            }

                            // 删除pc
                            var updEnt3 = new TgUserPcModel({
                                doc_id: docId,
                                update_by: userId
                            });
                            updEnt3.delPcLogic(function(updErr3){
                                if (updErr3) {
                                    console.log('tg.js [delUserDoc] Del Pc Err: ' + updErr3);
                                    return ret_func(0,CODE.OPERATION_FAILED);
                                }

                                return ret_func(1,CODE.OPERATION_SUCCESS);
                            });
                        });
                    });

                } else {
                    console.log('tg.js [delUserDoc] Doc Not Found');
                    return ret_func(1,CODE.OPERATION_SUCCESS);
                }
            });
        } else {
            // 用户不存在时
            console.log('tg.js [delUserDoc] User Not Found');
            return ret_func(0,CODE.UNKNOWN_USER);
        }
    });
}
router.get('/delUserDoc', delUserDoc);
router.post('/delUserDoc', delUserDoc);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取[设计模版]或[用户作品]预览图(无预览时自动排版一次)及切换历史记录(注意：印品模版去除了出血)
 * 方式:GET/POST
 * 参数 device: 请求来源
 * 参数 uuid: 设备标识
 * 参数 docId: 文档id
 * 参数 isDesign: 1:    docId为[设计模版]文档id,
 *               0或空: docId为[用户作品]文档id
 * 参数 userId: 用户id
 * 参数 typeL: 0 未分类   1 海报  2 多页  3 ppt.  4. 印品 //  从5.x开始增加此参数，注意之前的接口没有此参数
 * 返回:
     {
         "docId": 1,
         "docNm": 'design_name/doc_name',
         "designId": 2,// 仅获取[用户作品]时有效
         "designer" :{“id” : 756, “avatarUrl” : “http://oss-image-xx.png”},
         "size":{  // 模版或作品尺寸，注意：印品模版去除了出血
            "w":720,
            "h":1280
         },
         "preview":[
             {
                 "pageId": 4,
                 "index": 0,
                 "thumb": "xxx" // 注意：印品模版去除了出血
             }
         ],
         "history":[
            ...
         ],
         "price":1000// [V5_1新增]: 非印品模版价格
     }
 * 测试地址：http://localhost:3000/tg/getDocPreviewEx?his=1&docId=45696&device=1&isDesign=0&userId=64220&uuid=811BF5F4-5948-4C9B-AFA5-C8F4315B1DC9-iOS&typeL=4
 * */
function getDocPreviewEx(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var docId = Number(req.body.docId || req.query.docId || '0');
    var isDesign = Number(req.body.isDesign || req.query.isDesign || '0');
    var userId = Number(req.body.userId || req.query.userId || '0');
    var getHis = Number(req.body.his || req.query.his || '0');
    getHis=0; // 移除切换模板功能, 此处强制指定不获取历史记录, modify by 王俊 2018-04-18
    var typeL = Number(req.body.typeL || req.query.typeL || '0'); // 对于印品需要去除出血线


    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    if (typeof docId=='undefined' || isNaN(docId) || docId==null || docId==0) {
        return tgUtil.ret_func_json(0,'用户文档id为空',{},res);
    }
    //if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
    //    return tgUtil.ret_func_json(0,'无效用户id',{},res);
    //}


    // 获取文档
    var docEntity = null;
    if(isDesign) {
        docEntity = new TgDesignDocModel({
            design_id: docId,
            del_flg: 0
        });
    } else {
        docEntity = new TgUserDocModel({
            doc_id: docId,
            del_flg: 0,
            withoutPgInfo: 1// 新文档没有pg
        });
    }
    docEntity.getDocInfoById(function (findErr, docs) {
        if (findErr) {
            console.log('tg.js [getDocPreviewEx] find doc Err: ' + findErr);
            return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        if(docs && docs.length>0){
            var itemInfo = docs[0];

            // 获取preview
            var pgEntity = null;
            if(isDesign) {
                pgEntity = new TgDesignPageModel({
                    design_id: docId,
                    del_flg:0
                });
            }else{
                pgEntity = new TgUserPageModel({
                    doc_id: docId,
                    del_flg:0
                });
            }
            pgEntity.getPageInfoById(function(error, items){
                if(error){
                    console.log('tg.js [getDocPreviewEx] getPageInfoById Err: '+error);
                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }

                // process success
                var pageData = [];
                var doTypeset = false;
                if (items != null && items.length > 0) {
                    for (var i in items){
                        var item = items[i];

                        // 只要有未生成预览图的页面就返回error
                        if (item.thumb == null || item.thumb.trim().length == 0) {
                            doTypeset = true;
                            break;
                        }

                        // 组合page数据
                        var pageItem = {
                            pageId: item.page_id,
                            index: item.page_index,
                            thumb: item.thumb||''
                        };
                        pageData.push(pageItem);
                    }
                } else {
                    if(!isDesign) {// 新建用户文档无page,pc
                        doTypeset = true;
                    }
                }

                // 返回值
                var retData={
                    docId: docId,
                    preview: pageData,
                    price: Number(itemInfo.min_tmpl_price|| '0'),
                    vip : itemInfo.vip
                };
                // todo 客服电话
                retData.service = '17762500830';

                if (doTypeset) {
                    // 重新排版
                    rpcFunc.typesetTGDocImageOfDoc(docId, 3/*作品*/,function (error, images) { // 新方法：使用image工程
                    //rpcFunc.typesetTGDoc(docId,function (error, images) { // 旧方法：使用auto+image工程
                        if(error) return ret_func(0, '排版失败', null);
                        // 再次获取
                        pgEntity.getPageInfoById(function (error2, items2) {
                            if (error2) {
                                console.log('tg.js [getDocPreviewEx] Re-getPageInfoById Err: ' + error2);
                                return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                            }

                            // process success
                            pageData = [];
                            if (items2 != null && items2.length > 0) {
                                for (var n in items2) {
                                    var item = items2[n];

                                    // 只要有未生成预览图的页面就返回error
                                    if (item.thumb == null || item.thumb.trim().length == 0) {
                                        return tgUtil.ret_func_json(0,CODE.PAGE_THUMB_EMPTY,{},res);
                                    }

                                    // 组合page数据
                                    var pageItem = {
                                        pageId: item.page_id,
                                        index: item.page_index,
                                        thumb: item.thumb||''
                                    };
                                    pageData.push(pageItem);
                                }
                            }

                            // 更新预览
                            retData.preview = pageData;

                            if(isDesign){
                                // 设计文档名
                                retData.docNm = itemInfo.design_name||'';
                            } else {
                                // 当前用户文档所使用的设计模版id
                                retData.designId = itemInfo.design_id;
                                // 用户文档名
                                retData.docNm = itemInfo.doc_name||'';
                            }

                            // 获取切换历史
                            tgUtil.getSwitchHis(getHis, docId,userId, function(err, retHis){
                                if (err) {
                                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                                }
                                retData.history = retHis || [];

                                // 删除印品预览图的出血
                                tgUtil.adjust_size_of_image (typeL, docId, isDesign, retData.preview,function(err2,size){
                                    if(err2){
                                        return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                                    }
                                    retData.size = size; // 返回size
                                    return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
                                });

                            });

                        });
                    });
                } else {
                    // 无需排版
                    if(isDesign){
                        // 设计文档名
                        retData.docNm = itemInfo.design_name||'';
                    } else {
                        // 当前用户文档所使用的设计模版id
                        retData.designId = itemInfo.design_id;
                        // 用户文档名
                        retData.docNm = itemInfo.doc_name||'';
                    }

                    // 获取设计师信息
                    tgUtil.getUserInfo(itemInfo.user_id, function(error, userInfo){
                        if(userInfo){
                            retData.designer = {
                                "id":userInfo.user_id,
                                "avatarUrl":userInfo.head_url
                            };
                        }

                        // 获取切换历史
                        tgUtil.getSwitchHis(getHis, docId,userId, function(err, retHis){
                            if (err) {
                                return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                            }
                            retData.history = retHis || [];

                            // 获取 印品的出血
                            tgUtil.adjust_size_of_image (typeL, docId, isDesign, retData.preview,function(err2,size){
                                if(err2){
                                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                                }
                                retData.size = size; // 返回size
                                return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
                            });
                        });

                    });

                }
            });

        } else {
            return tgUtil.ret_func_json(0,"未检索到文档",{},res);
        }
    });

}
router.get('/getDocPreviewEx', getDocPreviewEx);
router.post('/getDocPreviewEx', getDocPreviewEx);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 切换模板
 * 方式:GET/POST
 * 参数 device: 请求来源
 * 参数 uuid: 设备标识
 * 参数 docId: 用户文档id
 * 参数 userId: 用户id
 * 参数 usedIds(可选): 切换过的模版id(数组字符串 '[1,2,3]')
 * 参数 toTmpl(可选): 切换到指定的模版
 * 参数 typeL: 0 未分类   1 海报  2 多页  3 ppt.  4. 印品 //  从5.x开始增加此参数，注意之前的接口没有此参数
 * 返回:
 {
     "success": 1,
     "msg": "成功",
     "data": {
         "designId": 100,// 当前切换到的模版id
         "preview": [
             {
                 "thumb": "http://itbour-generate.itbour.com/image/U8/2016/04/12/111736242_9195288177579642/0.jpg",
                 "pageId": 345,
                 "index": 0
             },
             {
                 "thumb": "http://itbour-generate.itbour.com/image/U8/2016/04/12/111736242_9195288177579642/0.jpg",
                 "pageId": 346,
                 "index": 1
             }
         ],
         "history": [ // 最后一个为当前 preview 对应的模板
             {
                 "designId": 1,
                 "thumb": "http://itbour-generate.itbour.com/image/U8/2016/04/12/111736242_9195288177579642/0.jpg"
             },
             ...
         ]
     }
 }
 * */
function switchTmpl(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var docId = Number(req.body.docId || req.query.docId || '0');
    var userId = Number(req.body.userId || req.query.userId || '0');
    var usedIds = JSON.parse(req.body.usedIds || req.query.usedIds || '[]');
    var toTmplId = Number(req.body.toTmpl || req.query.toTmpl || '0');
    var typeL = Number(req.body.typeL || req.query.typeL || '0'); //

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    if (typeof docId=='undefined' || isNaN(docId) || docId==null || docId==0) {
        return ret_func(0,"用户文档id为空");
    }
    if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
        return ret_func(0,"无效用户id");
    }

    var url = CONFIG.SWITCH_SERVER_DOMAIN +':'+CONFIG.SWITCH_SERVER_PORT;
    if(toTmplId && toTmplId>0) {
        // 指定切换
        url+= '/tgSwitch/switchTo?'
            +'docId='+docId
            +'&userId='+userId
            +'&tmplId='+toTmplId;
    } else {
        // 随机切换
        url+= '/tgSwitch/switchTmpl?'
            +'docId='+docId
            +'&userId='+userId
            +'&usedIds='+JSON.stringify(usedIds);
    }

    superagent.get(url)
        .end(function(err, res){
            if(err){
                console.log('tg.js [switchTmpl] SuperAgent get Err: ' + err);
                return ret_func(0, CODE.OPERATION_FAILED);
            }

            console.log('tg.js [switchTmpl] SuperAgent get:\n'+res.text);
            var retJson = JSON.parse(res.text);
            if(retJson.success){

                // 获取preview
                var entity = new TgUserPageModel({
                    doc_id: docId
                });
                entity.getPageInfoById(function(error, items){
                    if(error){
                        console.log('tg.js [switchTmpl] getPageInfoById Err: '+error);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    // process success
                    var pageData = [];
                    if (items != null && items.length > 0) {
                        for (var i in items){
                            var item = items[i];

                            // 组合page数据
                            var pageItem = {
                                pageId: item.page_id,
                                index: item.page_index,
                                thumb: item.thumb||''
                            };
                            pageData.push(pageItem);
                        }
                    }

                    var retData={
                        designId: retJson.data.designId||'',
                        preview: pageData,
                        history: retJson.data.history||[]
                    };

                    return ret_func(1,CODE.OPERATION_SUCCESS,retData);
                });
            } else {
                return ret_func(0, retJson.msg);
            }
        });
}
router.get('/switchTmpl', switchTmpl);
router.post('/switchTmpl', switchTmpl);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取文档的预览图.
 * 方式:GET
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:docId:文档id
 * 参数:title(可选) 微信分享用
 * 参数:content(可选) 微信分享用
 *
 * 测试地址：http://localhost:3000/tg/pDoc?docId=21&type=1
 * */
function pDoc(req, res, next) {
    //rpc调用image服务
    rpcFunc.createTGDocImage(req.query.docId, req.query.type, 0, function (ret) {
        try{
            var retJson = {
                success:1,
                msg:'success',
                pages:[]
            }
            var imgs = ret;
            // 转换成页面需要的结构

            for(var i=0;i<imgs.length;i++){
                retJson.pages.push({
                    thumb_s:imgs[i],
                    page_index:i
                });
            }


            return res.render('indexDoc', retJson);
        }catch(e){
            return res.render('indexDoc', []);
        }
    });
}
router.get('/pDoc', pDoc);
router.post('/pDoc', pDoc);
//------------------------------------------------------------------



//------------------------------------------------------------------
/* 对竖屏用户作品的多页做拼接
 * 方式:GET
 * 参数 device: 请求来源
 * 参数 uuid: 设备标识
 * 参数 userId: 用户唯一标识
 * 参数 productId: 多页作品唯一标识
 * */
function montageImages(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var user_id = req.body.userId || req.query.userId;
    var doc_id = req.body.productId || req.query.productId;

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // check parameter
    if (typeof user_id=='undefined' || user_id==null
        ||typeof doc_id=='undefined' || doc_id==null) {
        return ret_func(0,"用户id或者文档id为空");
    }

    rpcFunc.montageImages(doc_id,  user_id, function(err, url){
        if(err){
            return ret_func(0,"拼接图片错误！");
        }
        return ret_func(1,'success',{bigImage:url});
    });
}
router.get('/montageImages', montageImages);
router.post('/montageImages', montageImages);



//------------------------------------------------------------------
/* 获取模版／作品的尺寸信息
 * 参数  docId: 文档id
 * 参数  isDesign: 1:    docId为[设计模版]文档id,
 *               0或空: docId为[用户作品]文档id
 * 参数：callback：回调，参数如下：
 *          error:错误消息
 *          data:tg_size的model
 *
 */
function getSizeOfDoc(req, res, next) {
    // get parameter
    var docId = req.body.docId || req.query.docId;
    var isDesign = req.body.isDesign || req.query.isDesign;

    tgUtil.get_size_of_doc(docId, isDesign, function(error, data){
        if(error){
            return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data, res);
    });
}
router.get('/getSizeOfDoc', getSizeOfDoc);
router.post('/getSizeOfDoc', getSizeOfDoc);
//------------------------------------------------------------------

module.exports = router;
